package tul.cot.job.output;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class LineSaver {
	private LinesGrouper grouper;

	public LineSaver(LinesGrouper grouper) {
		this.grouper = grouper;
	}
	
	public void saveLines(Iterable<String> lines, File outDir) throws IOException {
		
		// create output directory
		if (!outDir.exists()) {
			boolean created = outDir.mkdir();
			if (!created) {
				throw new IOException("Cannot create output dir");
			}
		}
		
		File file = null;
		FileWriter writer = null;
		
		for (String line: lines) {
			String fileName = grouper.getFileName(line);
			File outFile = new File(outDir, fileName);
			
			if (!outFile.equals(file)) {
				if (writer != null)
					writer.close();
				
				file = outFile;
				writer = new FileWriter(file);
				
				String header = grouper.getFileHeader(fileName);
				if (header != null)
					writer.write(header);
			}
			
			writer.write(grouper.transform(line) + "\n");
		}
		
		if (writer != null)
			writer.close();
	}
}
